use std::{io::Cursor, ops::Deref};

use rodio::{source::SamplesConverter, Decoder, OutputStream, OutputStreamHandle, Sink};
use thunderdome::{Arena, Index};
use QcCore::resources::audio_clip::AudioClip;

pub struct AudioEngine {
    stream: OutputStream,
    stream_handle: OutputStreamHandle,
    pool: Arena<Sink>,
}

impl AudioEngine {
    pub fn new() -> Self {
        let (stream, stream_handle) = OutputStream::try_default().unwrap();

        Self {
            stream,
            stream_handle,
            pool: Arena::new(),
        }
    }

    pub fn play(&self, clip: Cursor<Vec<u8>>) -> Result<Sink, rodio::PlayError> {
        self.stream_handle.play_once(clip)
    }

    pub fn pause(&self, sink: Sink) {
        sink.pause();
    }

    pub fn add_sink(&mut self, sink: Sink) -> Index {
        self.pool.insert(sink)
    }

    pub fn get_sink(&mut self, index: Index) -> Option<&Sink> {
        self.pool.get(index)
    }
}
